
#include "StdAfx.h"
#include "UserManager.h"
#include <LogService.h>

UserManager::UserManager(){
}

UserManager::~UserManager(){
}

size_t UserManager::size(){
	size_t numeric = numeric_key_.size();
	size_t str = str_key_.size();

	if( numeric == str )
		return numeric;

	LOG_DEBUG( LOG_SERVICE( "instance" )->Log("%s - %u : num : %u / str : %u", __FUNCTION__, __LINE__, numeric, str ) );
	
	if( numeric > str )
		return numeric;
	return str;
}

User* UserManager::get( size_t ident ){	
	return numeric_key_.get( ident );	
}

User* UserManager::get( char* id ){	
	if(! id )
		return 0;

	return str_key_.get( id );
}

bool UserManager::add( User* user ){
	IS_NULL_RETURN( user, false );	

	size_t ident = user->getIdent();
	if(! ident )
		return false;
	
	return numeric_key_.add( ident, user );		
}

bool UserManager::user_just_login( User* user ){
	char* id = (char*)user->getID();

	if(! strlen( id ) )
		return false;

	if(! str_key_.add( id, user ) ){
//		user->setID( " " );
		return false;
	}

	return true;
}

void UserManager::remove( User* user ){
	size_t ident = user->getIdent();
	char* id = (char*)user->getID();

	numeric_key_.remove( ident );

	if(! id )
		return;

	User* target = str_key_.get( id );
	if(! target )
		return;

	if( target->getIdent() == ident )
		str_key_.remove( id );
}

int UserManager::broadcast_all( char* data, size_t size ){
	IS_NULL_RETURN( data, 0 );
	IS_NULL_RETURN( size, 0 );
	
	int count = 0;
	User* user = 0;

	numeric_key_.resetCursor();
	while(! numeric_key_.isEnd() ){
		user = numeric_key_.getCurrentValue();
		IS_NULL_ACTION( user, break );

		user->send( data, size );

		count++;
		numeric_key_.nextCursor();
	}		

	return count;	
}

int UserManager::broadcast( char* data, size_t size ){
	IS_NULL_RETURN( data, 0 );
	IS_NULL_RETURN( size, 0 );	

	int count = 0;
	User* user = 0;

	str_key_.resetCursor();
	while(! str_key_.isEnd() ){
		user = str_key_.getCurrentValue();
		IS_NULL_ACTION( user, break );

		user->send( data, size );

		count++;
		str_key_.nextCursor();
	}

	return count;	
}
